import { onPageScroll } from '@dcloudio/uni-app'
import { computed, onMounted, reactive } from 'vue'

export default function useSysMixin() {
  const _initPageScroll = (callback) => {
    onPageScroll((e) => {
      uni.$emit(`_scrollTop_`, e.scrollTop)
      // 调用回调函数，并传递事件对象
      if (callback && typeof callback === 'function') {
        callback(e)
      }
    })
  }
  onMounted(() => {})
  const state = reactive({
    sys_homePath: '/pages/base/index', // 请根据实际情况设置默认值
  })

  const sysIsFirstPage = computed(() => {
    // 实例是否为路由栈的第一个页面
    const pages = getCurrentPages()
    return pages.length === 1
  })

  const isPc = computed(() => {
    return uni.getSystemInfoSync().windowWidth > 750
  })

  const _backPage = (number = 1) => {
    if (sysIsFirstPage.value) {
      _toHome()
    }
    else {
      uni.navigateBack({
        delta: number,
        fail(res) {
          console.log(res)
        },
      })
    }
  }

  const _toHome = () => {
    uni.switchTab({
      url: state.sys_homePath,
      fail: (res) => {
        console.log(res)
        _to(state.sys_homePath)
      },
    })
  }

  const _to = (url, type = '') => {
    switch (type) {
      case 'switchTab':
        uni.switchTab({
          url,
          fail(res) {
            console.log(res)
          },
        })
        break
      case 'reLaunch':
        uni.reLaunch({
          url,
          success(res) {
            console.log(res)
          },
          fail(res) {
            console.log(res)
          },
        })
        break
      case 'redirectTo':
        uni.redirectTo({
          url,
          fail(res) {
            console.log(res)
          },
        })
        break
      default:
        uni.navigateTo({
          url,
          fail(res) {
            console.log(res)
          },
        })
        break
    }
  }

  const _addCommasToNumber = (number = 0) => {
    return (`${number}`).replace(/\d(?=(\d{3})+$)/g, '$&,')
  }
  const _previewPdf = (item: any) => {
    if (item.url.includes('.pdf')) {
      uni.navigateTo({
        url: `/pages/work/pdf?url=${encodeURIComponent(encodeURIComponent(item.url))}`,
      })
    }
    else {
      uni.navigateTo({
        url: `/pages/base/web?url=${encodeURIComponent(item.url)}`,
      })
    }
  }

  return {
    sysIsFirstPage,
    isPc,
    _backPage,
    _toHome,
    _to,
    _addCommasToNumber,
    _initPageScroll,
    _previewPdf,
  }
}
